<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use app\admin\model\order\Order;
use think\Db;
use wxpay\Delivery;
use wxpay\Kuaidi;

/**
 * 快递管理
 *
 * @icon fa fa-circle-o
 */
class Courier extends Backend
{

    /**
     * Courier模型对象
     * @var \app\admin\model\order\Courier
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Courier;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查询快递是否收件
     */
    public function courierselect($ids = '')
    {
        $order = Order::get($ids);
        $couri = $this->model->where('order_pay_sn',$order['order_sn'])->find();
        $couri["delivery_name"] = $order["delivery_name"];
        $couri["mobile"] = $order["mobile"];
        if (empty($couri))
        {
            $this->error('订单不存在');
        }

        if (empty($couri['waybill']))
        {
            $this->error('请查询该订单是否下单');
        }

        // $delivery = new Delivery();
        $Kuaidi = new Kuaidi();
        $response = $Kuaidi->synquery($couri);
        $response["orderId"] = $order["order_sn"];
        // dump($response);
        // die;
        if ($response['status'] == 200)
        {
            if ($couri['filterStatus'] == 2)
            {
                $couri->filterStatus = 2;
                $res = $couri->save();
            }
            $this->view->assign('row',$response);
            return $this->view->fetch();
        }else{
            $this->error($response['msg']);
        }
    }

    /**
     * 查询快递数量
     */
    public function orderquery($ids = '')
    {
        $courierData = $this->model->get($ids);
        if (empty($courierData) || empty($courierData['waybill']))
        {
            $this->error('物流信息不存在');
        }

        if ($courierData['filterStatus'] == 2)
        {
            $this->error('包裹已揽收无法取消');
        }

        if ($courierData['filterStatus'] == 3)
        {
            $this->error('订单已取消发货');
        }

        $Delivery = new Delivery();

        $response = $Delivery->orderCancel($courierData['order_pay_sn']);

        if ($response['status'] == true)
        {
            $courierData->filterStatus = 3;
            $courierData->save();
            $this->success($response['msg']);
        }else{
            $this->error($response['msg']);
        }

    }

    /**
     * 打印快递
     */
    public function print()
    {
        $Delivery = new Delivery();
        $response = $Delivery->orderPrint();
    }
}
